package com.wu.ssm.spring.ioc;

import com.wu.ssm.spring.annotion.MyQualifier;
import com.wu.ssm.spring.utils.ReflectionUtil;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by wzf on 2018/11/28/028.
 */
public class IocHelper {

    // 自动注入的核心方法
    static {
        System.out.println("自动注入的核心方法执行了");
        Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
        if(!CollectionUtils.isEmpty(beanMap)){
            // 遍历所有的bean
            for (Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()
                 ) {
                Class<?> beanClazz = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                // 获取bean定义的所有成员变量
                Field [] fields = beanClazz.getDeclaredFields();
                if(fields.length > 0){
                    for (Field beanField:fields
                         ) {
                        // 自动注入带有MyQualifier注解的成员变量
                        if(beanField.isAnnotationPresent(MyQualifier.class)){
                            Class<?> fieidClazz = beanField.getType();
                            Object fieldInstance = beanMap.get(fieidClazz);
                            if(fieldInstance != null){
                                ReflectionUtil.setFeild(beanInstance,beanField,fieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
